import Taro from '@tarojs/taro';
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import { useCallback, useContext, useState } from 'react';
import { ChagePersonalInfoContext } from '../ChagePersonalInfoContext';
import { apiGetChageAvatar } from '@/pages/_server/_api/ChagePersonalInfo/apiGetChageAvatar';

export const useChangeAvatar = () => {
    const { setShowComponent } = useContext(ChagePersonalInfoContext);
    const [fileList, setFileList] = useState<any>([]);
    const [isActiveConfirmBtn, setIsActiveConfirmBtn] = useState<boolean>(false);
    const cancel = useCallback(() => {
        console.log('修改昵称');
        setShowComponent('BaseInfo');
    }, [setShowComponent]);

    const confirm = useCallback(async () => {
        console.log('修改昵称');
        if (!fileList.length) return;
        const formData = new FormData();
        formData.append('file', fileList[0].file);
        const res = await apiGetChageAvatar(formData);
        if (!res) return;
        setShowComponent('ChangeAvatar');
    }, [fileList, setShowComponent]);

    const upload = useCallback(async (file: File) => {
        await setTimeout(() => {}, 3000);
        return {
            file: file,
            url: URL.createObjectURL(file),
        };
    }, []);

    const beforeUpload = useCallback((file: File) => {
        if (file.size > 1024 * 1024) {
            Taro.showToast({
                title: '必须小于2M',
                icon: 'none',
                duration: 2000,
            });
            return null;
        }
        setIsActiveConfirmBtn(true);
        return file;
    }, []);

    const onDelete = useCallback(() => {
        setIsActiveConfirmBtn(false);
    }, []);
    return {
        isActiveConfirmBtn,
        fileList,
        setFileList,
        cancel,
        onDelete,
        confirm,
        upload,
        beforeUpload,
    };
};
